package com.ktjy.controller;

import com.google.code.kaptcha.Producer;
import com.ktjy.utils.AjaxResult;
import com.ktjy.utils.Constants;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api")
@Tag(name="验证码模块")
public class CaptchaController {
    @Resource
    Producer captchaProducerMath;
    @Resource
    RedisTemplate redisTemplate;

    @GetMapping("/captcha")
    @Operation(summary = "验证码接口")
    public AjaxResult captcha(HttpSession session){
        // 生成验证码
        String capText = captchaProducerMath.createText();
        System.out.println(capText);
        //截取的算式
        String capStr = capText.substring(0, capText.lastIndexOf("@"));
        //截取的答案
        String code = capText.substring(capText.lastIndexOf("@") + 1);

        //将算式转换成图片
        BufferedImage image = captchaProducerMath.createImage(capStr);
        //将图片转换成字节数组
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //将答案保存到session中
//        session.setAttribute(Constants.CAPTCHA,code);
        //将答案保存到redis中
        String uuid=UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(Constants.CAPTCHA+uuid,code,30, TimeUnit.SECONDS);

        AjaxResult ajaxResult=AjaxResult.success(os.toByteArray());
        ajaxResult.put("uuid",uuid);
        return ajaxResult;
    }


}
